package com.duojuhe.common.utils.dingding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DingDingUtil {
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String BASE_URL = "https://oapi.dingtalk.com/robot/send";
    private static OkHttpClient client;

    /**
     * 发送钉钉机器人通知
     * @param accessToken
     * @param title
     * @param content
     */
    public static void sendToRobot(String accessToken, String title, String content) {
        try {
            if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(title) || StringUtils.isBlank(content)) {
                log.error("【系统错误钉钉通知】DingDing robot send fail, accessToken={}, title={}, content={}", accessToken, title, content);
                return;
            }
            HashMap<String, Object> body = new HashMap<String, Object>();
            body.put("msgtype", "markdown");
            Map<String, String> textContent = new HashMap<String, String>();
            textContent.put("text", "** " + title + "**\n #### " + content);
            textContent.put("title", title);
            body.put("markdown", textContent);
            RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, JSON.toJSONString(body));
            Request request = (new Builder()).url(BASE_URL + "?access_token=" + accessToken).post(requestBody).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    String result = responseBody.string();
                    JSONObject jsonObject = JSON.parseObject(result);
                    if (jsonObject.getIntValue("errcode") == 0) {
                        log.error("【系统错误钉钉通知】DingDing robot send success, title={}, content={}", title, content);
                        return;
                    }
                    log.error("【系统错误钉钉通知】DingDing robot send fail, accessToken={}, title={}, content={} result={}", accessToken, title, content, result);
                    return;
                }
            }
            log.error("【系统错误钉钉通知】DingDing robot send error, accessToken={}, title={}, content={}", accessToken, title, content);
        } catch (Exception e) {
            log.error("【系统错误钉钉通知】DingDing robot send error, accessToken={}, title={}, content={}", accessToken, title, content, e);
        }
    }

    static {
        ConnectionPool pool = new ConnectionPool(1, 180L, TimeUnit.SECONDS);
        client = (new OkHttpClient.Builder()).connectTimeout(20L, TimeUnit.SECONDS).readTimeout(20L, TimeUnit.SECONDS).connectionPool(pool).followRedirects(false).retryOnConnectionFailure(true).build();
    }
}